//
//  IMContentManager.m
//  TQY
//
//  Created by 甘世清 on 2024/10/29.
//

#import "IMContentManager.h"

@implementation IMContentManager
 
+(void)SQ_settextLayout:(IMMessageModel*)model{
   
    NSMutableAttributedString *text = [IMContentManager attributedStringWithText:model.content  emojiMapper:[IMSendMessageManager emjonDict] isList:model.isSend handler:nil];
    model.textLayout  = [YYTextLayout layoutWithContainerSize:CGSizeMake(SCREEN_WIDETH-140, 5000)
                                                  text:text];
}

/// 时间字符串计算
/// - Parameter sendTime: 时间戳
+(NSString*)SQ_getTimeString:(NSString*)sendTime{
   NSString * showTime = [NSString SQ_time:sendTime Formatter:@"HH:mm"];//当前时间
    NSString* newTime = [NSString SQ_time:sendTime Formatter:@"yyyy年MM月dd日 HH:mm:ss"];//总时间
    NSString * toDay = [NSString SQ_getUTCFormateDate:newTime];
    if ([toDay isNotEmpty]) {
        if ([toDay isEqualToString:@"其他时间"]) {//如果是昨天的
           showTime = [NSString SQ_time:sendTime Formatter:@"MM月dd日 HH:mm"];
        }else{
             showTime = [NSString stringWithFormat:@"%@ %@",toDay,showTime];
        }
    }
    return showTime;
}
+ (NSMutableAttributedString *)attributedStringWithText:(NSString *)text emojiMapper:(NSMutableDictionary *)emojiMapper isList:(BOOL)isList handler:(void(^)(BOOL isTap, int strType, NSString *targetString))handler
{      //转成可变属性字符串
        NSMutableAttributedString * mAttributedString = [[NSMutableAttributedString alloc]init];
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        [paragraphStyle setLineSpacing:4];//调整行间距
        [paragraphStyle setParagraphSpacing:4];//调整行间距
    NSDictionary *attri = [NSDictionary dictionaryWithObjects:@[FONT_REGULAR(16),isList?SQColor(@"#212121"):[UIColor whiteColor],paragraphStyle] forKeys:@[NSFontAttributeName,NSForegroundColorAttributeName,NSParagraphStyleAttributeName]];
        [mAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:text attributes:attri]];
        //创建匹配正则表达式的类型描述模板
        NSString * pattern = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";
        //创建匹配对象
        NSError * error;
        NSRegularExpression * regularExpression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:&error];
        if (!regularExpression)//如果匹配规则对象为nil
        {  return nil; }
        else
        {  NSArray * resultArray = [regularExpression matchesInString:mAttributedString.string options:NSMatchingReportCompletion range:NSMakeRange(0, mAttributedString.string.length)];
            //开始遍历 逆序遍历
            for (NSInteger i = resultArray.count - 1; i >= 0; i --)
            {   //获取检查结果，里面有range
                NSTextCheckingResult * result = resultArray[i];
                //根据range获取字符串
                NSString * rangeString = [mAttributedString.string substringWithRange:result.range];
                NSString *imageName =  rangeString;
                if (imageName)
                {   //获取图片
                    YYImage * image = emojiMapper[imageName];//这是个自定义的方法
                    if (image != nil)
                    {
                        image.preloadAllAnimatedImageFrames = YES;
                        YYAnimatedImageView *imageView = [[YYAnimatedImageView alloc] initWithImage:image];
                        NSMutableAttributedString *attachText = [NSMutableAttributedString yy_attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.bounds.size alignToFont:FONT_REGULAR(16) alignment:YYTextVerticalAlignmentCenter];
                        //开始替换
                        [mAttributedString replaceCharactersInRange:result.range withAttributedString:attachText];
                    }
                }
            }
        }
   
        // 高亮 点击
        NSMutableArray *highlightRanges = [NSMutableArray array];
        [highlightRanges addObjectsFromArray:[self tagResultsWithAttributeString:mAttributedString]];
        [highlightRanges addObjectsFromArray:[self emailResultsWithAttributeString:mAttributedString]];
        [highlightRanges addObjectsFromArray:[self urlResultsWithAttributeString:mAttributedString]];
        [highlightRanges addObjectsFromArray:[self phoneResultsWithAttributeString:mAttributedString]];
        WS(weakSelf);
        for (NSDictionary *rangeDict in highlightRanges) {
            if (![rangeDict isKindOfClass:[NSDictionary class]]) continue;
            // 获取高亮文本类型
            NSNumber *typeNum = [rangeDict allKeys][0];
            NSValue *rangeValue = [rangeDict objectForKey:typeNum];
            NSRange range = [rangeValue rangeValue];
            [mAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)SQColor3DA59D.CGColor range:range];
            // 1. 创建一个"高亮"属性，当用户点击了高亮区域的文本时，"高亮"属性会替换掉原本的属性
//            YYTextBorder *highlightBorder = [YYTextBorder borderWithFillColor:[UIColor colorWithWhite:0.2 alpha:0.2f] cornerRadius:3];
          
            YYTextHighlight *highlight = [YYTextHighlight new];
            [highlight setColor:SQColor3DA59D];
//            [highlight setBackgroundBorder:highlightBorder];
            [highlight setTapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
                // 点击回调
                NSString * rangeString = [text.string substringWithRange:range];
                [weakSelf richTextTouchAction:[typeNum intValue] value:rangeString];
            }];
            [highlight setLongPressAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
                // 长按回调
                NSString * rangeString = [text.string substringWithRange:range];
                [weakSelf richTextLongTouchAction:[typeNum intValue] value:rangeString];
            }];
            
            // 2. 把"高亮"属性设置到某个文本范围
            [mAttributedString yy_setTextHighlight:highlight range:range];
        }
    //    [mAttributedString setlong]
        return mAttributedString;
    
}
// 获取tag的range
+ (NSArray *)tagResultsWithAttributeString:(NSMutableAttributedString *)attString
{
    NSMutableArray *regularResults = [NSMutableArray array];
    NSMutableString * attStr = attString.mutableString;
    NSError *error = nil;//@"[\\$#@]\\{[a-zA-Z0-9_:\\u3400-\\u9FFF]{1,20}\\}|\\[[a-zA-Z0-9_\\u3400-\\u9FFF]+\\]";
    //[a-zA-Z0-9_:\\u3400-\\u9FFF]{1,20}
    NSString *regulaStr = @"<tag type='[a-zA-Z0-9_]*' value='((?!<\\/tag>).)*'>((?!<\\/tag>).)*</tag>";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    if (error == nil)
    {
        NSArray *arrayOfAllMatches = [regex matchesInString:attStr
                                                    options:0
                                                      range:NSMakeRange(0, [attStr length])];
        NSInteger forIndex = 0;
        NSInteger startIndex = -1;

        for (NSTextCheckingResult *match in arrayOfAllMatches){
            NSRange matchRange = match.range;

            if(startIndex == -1){
                startIndex = matchRange.location;
            }else{
                startIndex = matchRange.location-forIndex;
            }

            NSString* substringForMatch = [attStr substringWithRange:NSMakeRange(startIndex, matchRange.length)];

            NSString * contentStr = nil;
            NSString * replaceStr = nil;

            NSArray * contentArr = [substringForMatch componentsSeparatedByString:@"'>"];
            if(contentArr.count != 2){
                continue;
            }
            NSArray * contentArr0 = [contentArr[0] componentsSeparatedByString:@"'"];

            NSString * t_str = contentArr[1];

            NSString * tagType = contentArr0[1];//[contentArr[0] componentsSeparatedByString:@"'"][1];

            contentStr = contentArr0[3];

            NSString * tagName = nil;

            //这里的tagName写死了，写别的不知道为什么会给标签图片和文本之间留空格...
            if([tagType isEqualToString:@"image"]){
                tagName = @"[linkp]";
            }else if ([tagType isEqualToString:@"video"]){
                tagName = @"[linkv]";
            }else if ([tagType isEqualToString:@"link"]){
                tagName = @"[linka]";
            }else{
                continue;
            }
            replaceStr = [NSString stringWithFormat:@"%@%@",tagName,[t_str substringWithRange:NSMakeRange(0, t_str.length-6)]];

            [attString replaceCharactersInRange:NSMakeRange(startIndex, matchRange.length) withString:replaceStr];

            NSRange range = NSMakeRange(startIndex, replaceStr.length);

//            [attString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)KATUrlColor.CGColor range:range];
//            [attString addAttribute:@"keyAttribute" value:[NSString stringWithFormat:@"T%@{%@}",contentStr,[NSValue valueWithRange:range]] range:range];
            // 高亮文本类型为4
            [regularResults addObject:@{@4 : [NSValue valueWithRange:range]}];

            forIndex += substringForMatch.length-replaceStr.length;

            //            NSLog(@"attString: %@",attString.string);

        }

    }
    return regularResults;
}
// 获取email的range
+ (NSArray *)emailResultsWithAttributeString:(NSMutableAttributedString *)attString
{
    NSMutableArray *regularResults = [NSMutableArray array];

    NSMutableString * attStr = attString.mutableString;
    NSError *error = nil;;
    NSString *regulaStr = @"[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}";
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];

    if (error == nil)
    {
        NSArray *arrayOfAllMatches = [regex matchesInString:attStr
                                                    options:0
                                                      range:NSMakeRange(0, [attStr length])];

        for (NSTextCheckingResult *match in arrayOfAllMatches){
            NSRange matchRange = match.range;
            NSValue * valueRange = [NSValue valueWithRange:matchRange];

//            NSString* substringForMatch = [attStr substringWithRange:matchRange];

//            [attString addAttribute:(NSString *)kCTForegroundColorAttributeName value:(id)KATUrlColor.CGColor range:matchRange];
//
//            [attString addAttribute:@"keyAttribute" value:[NSString stringWithFormat:@"E%@{%@}",substringForMatch,valueRange] range:matchRange];
//            if(styleModel.emailUnderLine){
//                [attString addAttribute:(NSString *)kCTUnderlineStyleAttributeName value:(id)[NSNumber numberWithInt:kCTUnderlineStyleSingle] range:matchRange];
//            }
            // 高亮文本类型为3
            [regularResults addObject:@{@3 : valueRange}];
        }
    }

    return regularResults;
}

// 获取url的range
+ (NSArray *)urlResultsWithAttributeString:(NSMutableAttributedString *)attString
{
    NSMutableArray *regularResults = [NSMutableArray array];

    NSMutableString * attStr = attString.mutableString;
    NSError *error = nil;
    NSString *regulaStr = [NSString stringWithFormat:@"<a href='(((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%@^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%@^&*+?:_/=<>]*)?))'>((?!<\\/a>).)*<\\/a>|(((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%@^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%@^&*+?:_/=<>]*)?))",@"%",@"%",@"%",@"%"];//(<a href='%@'>[^<>]*</at>)
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSInteger forIndex = 0;
    NSInteger startIndex = -1;
    //    NSLog(@"o__str:  %@",attString.string);
    if (error == nil)
    {
        NSArray *arrayOfAllMatches = [regex matchesInString:attStr
                                                    options:0
                                                      range:NSMakeRange(0, [attStr length])];

        for (NSTextCheckingResult *match in arrayOfAllMatches){
            NSRange matchRange = match.range;

            if(startIndex == -1){
                startIndex = matchRange.location;
            }else{
                startIndex = matchRange.location-forIndex;
            }

            NSString* substringForMatch = [attStr substringWithRange:NSMakeRange(startIndex, matchRange.length)];
 
            NSString * contentStr = nil;
            NSString * replaceStr = nil;

            if([substringForMatch hasPrefix:@"<a"]){

                NSArray * contentArr = [substringForMatch componentsSeparatedByString:@"'>"];
                contentStr = [contentArr[0] componentsSeparatedByString:@"'"][1];

                NSString * t_str = contentArr[1];

                NSString * url_pre = @"[linka]";

                replaceStr = [NSString stringWithFormat:@"%@%@",url_pre,[t_str substringWithRange:NSMakeRange(0, t_str.length-4)]];

                [attString replaceCharactersInRange:NSMakeRange(startIndex, matchRange.length) withString:replaceStr];

                NSRange range = NSMakeRange(startIndex, replaceStr.length);
 

                [regularResults addObject:[NSValue valueWithRange:range]];

                forIndex += substringForMatch.length-replaceStr.length;
            }else{

                replaceStr = [NSString stringWithFormat:@"%@",substringForMatch];

                [attString replaceCharactersInRange:NSMakeRange(startIndex, matchRange.length) withString:replaceStr];

                NSRange range = NSMakeRange(startIndex, replaceStr.length);
 
                // 高亮文本类型为1
                [regularResults addObject:@{@1 : [NSValue valueWithRange:range]}];

                //                forIndex -= 4;
                forIndex += substringForMatch.length-replaceStr.length;
            }
        }
    }

    return regularResults;
}

// 获取手机号的range
+ (NSArray *)phoneResultsWithAttributeString:(NSMutableAttributedString *)attString
{
    NSMutableArray *regularResults = [NSMutableArray array];

    NSMutableString * attStr = attString.mutableString;
    NSError *error = nil;
 
    NSString *regulaStr=@"^(0[0-9]{2})\\d{8}$|^(0[0-9]{3}(\\d{7,8}))$|(1[34578][0-9]{9})";
 
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    if (error == nil)
    {
        NSArray *arrayOfAllMatches = [regex matchesInString:attStr
                                                    options:0
                                                      range:NSMakeRange(0, [attStr length])];

        for (NSTextCheckingResult *match in arrayOfAllMatches){

            NSRange matchRange = match.range;
 
            // 高亮文本类型为2
            [regularResults addObject:@{@2 : [NSValue valueWithRange:matchRange]}];
 
        }
    }

    return regularResults;
}

+(void)richTextTouchAction:(NSInteger)type value:(NSString *)value
{
    switch (type) {
        case 1:
        {
            //网址
            CommonWebVcView *vc = [CommonWebVcView new];
            vc.urlStr = value;
            [[UIView getCurrentVC].navigationController pushViewController:vc animated:YES];
        }

            break;
        case 2:
        {
            //电话
            NSString * str=[[NSString alloc] initWithFormat:@"telprompt://%@",value];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str] options:@{} completionHandler:^(BOOL success) {
            }];
        }
            break;
        default:
            break;
    }
}
+(void)richTextLongTouchAction:(NSInteger)type value:(NSString *)value
{
   
    
}
 
 
+(NSMutableDictionary *)getTouchEmjonDict
{
    NSMutableDictionary *_emjonDict = [NSMutableDictionary new];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"expression" ofType:@"plist"];
    NSDictionary *smileDict = [[NSDictionary alloc] initWithContentsOfFile:path];
    [smileDict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        UIImage *immm = [UIImage imageNamed:obj];
        NSData *imageData = UIImagePNGRepresentation(immm);
        YYImage *image = [YYImage imageWithData:imageData scale:2];
        image.preloadAllAnimatedImageFrames = YES;
        [_emjonDict setObject:image forKey:key];
    }];
    return _emjonDict;
}
@end
